<?php
/**
 * @fileName:XssClean.php
 * @project: miaosang
 * @nameSpace:miaosang\yii2\safety
 * @Class XssClean
 * @author : 吐火青蛙
 * @user : 吐火青蛙
 * @date : 2021-08-23 17:04
 * @desc : XssClean
 * @Copyright (c)  2021,All Rights Reserved.
 */

namespace miaosang\yii2\safety;

class XssClean
{
	/**
	 * @name removeXss
	 * @desc 对POST，GET,REQUEST,COOKIES,SERVER 进行XSS 过滤
	 */

	public static function removeXss()
	{
		if (!empty($_POST)) $_POST = self::filter($_POST);
		if (!empty($_GET))   $_GET = self::filter($_GET);
		if (!empty($_COOKIE)) $_COOKIE = self::filter($_COOKIE);
		if (!empty($_REQUEST)) $_REQUEST = self::filter($_REQUEST);
		if (!empty($_SERVER)) $_SERVER = self::filter($_SERVER);
	}

	/**
	 * @name filter
	 * @desc 对传入的参数进行XSS过滤
	 * @param array $data
	 * @return array
	 */
	public static function filter(array $data): array
	{
		array_walk_recursive($data, function (&$value) {
			// 处理NULL 数据,Null 转为空字符串
			if ($value === null) {
				$value = '';
			}
			//不对magic_quotes_gpc转义过的字符使用addslashes(),避免双重转义。
			if (!get_magic_quotes_gpc()) {
				//给单引号（'）、双引号（"）、反斜线（\）与 NUL（NULL 字符）加上反斜线转义
				$value = addslashes($value);
			}
			$value = htmlspecialchars($value, ENT_QUOTES);
		});
		return $data;
	}

}